package com.summer.entity;

import com.summer.mapper.IBackConfigParamsDao;
import com.summer.util.BackConfigParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class DictionaryCache implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DictionaryCache.class);

    public static ConcurrentMap<String,BackConfigParams> cacheMap = new ConcurrentHashMap<>();
    public static ConcurrentMap<String,Map<String,String>> translateMap = new ConcurrentHashMap<>();


    @Resource
    private IBackConfigParamsDao backConfigParamsDao;


    @Override
    public void run(String... args) throws Exception {
        //开始启动缓存加载服务
        addCacheData();
    }

    public void clearCacheMap(){
        cacheMap.clear();
        translateMap.clear();
    }

    public void reSetCacheMap(){
        clearCacheMap();
        addCacheData();
    }

    private void addCacheData(){
        List<BackConfigParams> backDictionaryList = backConfigParamsDao.findParams(new HashMap<>());
        if(!CollectionUtils.isEmpty(backDictionaryList)){
            for(BackConfigParams backDictionary:backDictionaryList){
                final String sysKey = backDictionary.getSysKey();
                cacheMap.put(sysKey,backDictionary);
                String sysType = backDictionary.getSysType();
                final String sysValue = backDictionary.getSysValue();
                if(translateMap.containsKey(sysType)){
                    Map<String, String> stringStringMap = translateMap.get(sysType);
                    stringStringMap.put(sysKey, sysValue);
                }else {
                    Map<String, String> stringStringMap = new HashMap<String, String>(){{
                        put(sysKey, sysValue);
                    }};
                    translateMap.put(sysType,stringStringMap);
                }
            }
        }
    }

}
